<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="收银员" prop="cashier">
            <el-input v-model="queryParams.cashier" placeholder="请输入收银员" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="账号名称" prop="accountName">
            <el-input v-model="queryParams.accountName" placeholder="请输入账号名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="面值金额" prop="faceValue">
            <el-input v-model="queryParams.faceValue" placeholder="请输入面值金额" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['shop:cashierQrcode:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Remove" @click="handleClean" v-hasPermi="['shop:cashierQrcode:list']">清空</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Open" @click="handleOpenAll" v-hasPermi="['shop:cashierQrcode:list']">全部开启</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Close" @click="handleCloseAll" v-hasPermi="['shop:cashierQrcode:list']">全部关闭</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="shopCashierQrcodeList" class="tableEmpty">
        <el-table-column label="收银员ID" align="center" prop="cashier" width="200px" />
        <el-table-column label="账号名称" align="center" prop="accountName" />
        <el-table-column label="二维码类型" align="center" prop="qrcodeType" />
        <el-table-column label="二维码备注" align="center" prop="qrcodeNote">
          <template #default="scope">
            <span>{{ scope.row.qrcodeNote==null?"--":scope.row.qrcodeNote }}</span>
          </template>
        </el-table-column>
        <el-table-column label="面值金额/元" align="center" prop="faceValue">
          <template #default="scope">
            <span>{{ scope.row.faceValue/100 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="二维码" align="center" prop="qrcode" />
        <el-table-column label="二维码圖" align="center" prop="qrcode">
          <template #default="scope">
            <span> <el-icon @click="showQrcode(scope.row)"><grid /></el-icon></span>
          </template>
        </el-table-column>
        <el-table-column label="日使用限制" align="center" prop="usableTimes" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160px">
          <template #default="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <span>
              <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="上传二维码" placement="top">
              <el-button link type="primary" @click="handleImport(scope.row)" v-hasPermi="['shop:cashierQrcode:edit']">上传二维码</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改商店收银二维码对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="shopCashierQrcodeFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="账号标识" prop="accountKey">
          <el-input v-model="form.accountKey" placeholder="请输入账号标识" />
        </el-form-item>
        <el-form-item label="二维码" prop="product">
          <el-input v-model="form.qrcode" placeholder="请输入二维码" style="width: 310px" />
          <el-button icon="Upload" @click="handleImport(undefined)">上传</el-button>
        </el-form-item>
        <el-form-item label="面值金额" prop="paymentLink">
          <el-input v-model="form.faceValue" placeholder="请输入面值金额" />
        </el-form-item>
        <el-form-item label="可用次数" prop="paymentLink">
          <el-input v-model="form.usableTimes" placeholder="请输入可用次数，0表示不限制" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">
              {{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="qrcodeDialog.title" v-model="qrcodeDialog.visible" width="500px" append-to-body>
      <el-card>
        <el-row class="mt-8px" :gutter="8" justify="space-between">
          <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24" class="mb-8px">
            <div>
              <!--<canvas id="canvas" ref="canvasRef" />-->
              <span><el-link type="primary">{{ qrcodeUrl }}</el-link></span>
              <el-image :src="qrCodeContent" v-if="qrCodeContent" />
            </div>
          </el-col>
        </el-row>

      </el-card>
    </el-dialog>

    <el-dialog title="上传二维码图片" v-model="impDialog.visible" width="500px" append-to-body>
      <el-form ref="uploadFormRef" :model="uploadForm" label-width="120px">
        <el-input :model="uploadForm.id" hidden="hidden" />
      </el-form>
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        drag
        v-model:file-list="fileList"
        :data="uploadForm"
        :on-success="importSuccess"
        :on-error="importError"
        :action="uploadUrl"
        :auto-upload="false"
        :disabled="uploadLoading"
        :headers="uploadHeaders"
        name="qrcodeFile"
        accept=".jpg, .png"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          Drop file here or <em>click to upload</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            jpg/png files with a size less than 500kb
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button :disabled="uploadLoading" :loading="buttonLoading" type="primary" @click="submitImport">上 传</el-button>
          <el-button @click="cancelImport">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ShopCashierQrcode" lang="ts">
import qrcode from 'qrcode';
import { listShopCashierQrcode,changeCashierQrcodeStatus,addShopCashierQrcode, enableAll, disableAll } from '@/api/shop/cashierQrcode';
import { ShopCashierQrcodeVO, ShopCashierQrcodeQuery, ShopCashierQrcodeForm } from '@/api/retail/shopCashierQrcode/types';
import {Grid, UploadFilled} from "@element-plus/icons-vue";
import {getToken} from "@/utils/auth";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable','biz_payment_way'));

const shopCashierQrcodeList = ref<ShopCashierQrcodeVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const qrCodeContent = ref();
const qrcodeUrl = ref();

const shopCashierQrcodeFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();
const canvasRef = ref();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadUrl = baseUrl + "/shop/cashierQrcode/import";
const uploadLoading = ref(false);
const uploadFormRef = ref();
const uploadRef = ref();
const uploadHeaders = ref();
const fileList = ref([]);

const impDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const qrcodeDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ShopCashierQrcodeForm = {
  id: undefined,
  cashier: undefined,
  accountKey: undefined,
  accountName: undefined,
  qrcode: undefined,
  qrcodeType: undefined,
  qrcodeNote: undefined,
  faceValue: undefined,
  usableTimes: undefined,
  status: undefined,
}
const data = reactive<PageData<ShopCashierQrcodeForm, ShopCashierQrcodeQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cashier: undefined,
    accountKey: undefined,
    accountName: undefined,
    qrcode: undefined,
    qrcodeType: undefined,
    qrcodeNote: undefined,
    faceValue: undefined,
    usableTimes: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    accountKey: [
      { required: true, message: "账号标识不能为空", trigger: "blur" }
    ],
    qrcode: [
      { required: true, message: "二维码不能为空", trigger: "blur" }
    ],
    faceValue: [
      { required: true, message: "面值金额不能为空", trigger: "blur" }
    ],
    usableTimes: [
      { required: true, message: "可用次数不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
const uploadForm = ref({
  id : 0
})

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}
/** 查询商店收银员二维码列表 */
const getList = async () => {
  loading.value = true;
  const res = await listShopCashierQrcode(queryParams.value);
  shopCashierQrcodeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}
/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  shopCashierQrcodeFormRef.value?.resetFields();
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}
/** 清空 */
const handleClean = () => {

}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加收銀二維碼信息";
  uploadForm.value.id = 0;
}

/** 提交按钮 */
const submitForm = () => {
  shopCashierQrcodeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await addShopCashierQrcode(form.value).finally(() =>  buttonLoading.value = false);
      proxy?.$modal.msgSuccess("提交成功");
      dialog.visible = false;
      await getList();
    }
  });
}
/** 查看二维码 */
const showQrcode = (row: ShopCashierQrcodeVO) => {
  qrcodeDialog.visible = true;
  qrcodeDialog.title = "查看二维码";
  qrcodeUrl.value = row.qrcode;
  qrCodeContent.value = row.qrcodeImage;
  /**
  nextTick(() => {
    const canvas = document.getElementById('canvas');
    qrcode.toCanvas(canvas, row.qrcode);
  });
    **/
}
// 状态修改
const handleStatusChange = async (row: ShopCashierQrcodeVO) => {
  let text = row.status === 0 ? "启用" : "停用";
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.accountName + '"账号吗？');
    await changeCashierQrcodeStatus(row.id, row.status);
    proxy?.$modal.msgSuccess(text + "成功");
  } catch {
    row.status = row.status === 0 ? 1 : 0;
  }
}
const submitImport = async () => {
  if(fileList.value.length == 0) {
    proxy?.$modal.msgError("请选择文件");
    return
  }
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getToken(),
    Clientid: import.meta.env.VITE_APP_CLIENT_ID
  }
  //if(uploadForm.value.id && uploadForm.value.id>0)
  await proxy?.$modal.confirm('确认要上传覆盖该账号的二维码吗？');
  uploadLoading.value = true;
  uploadRef.value!.submit();
}

const importError = () => {
  fileList.value = []
  uploadLoading.value = false;
}
/** 导入提交后 */
const importSuccess = (response: any) => {
  uploadLoading.value = false;
  if(response.code==200) {
    if(dialog.visible) {
      form.value.qrcode = response.msg;
    }
    proxy?.$modal.msgSuccess("上传成功");
    impDialog.visible = false;
    fileList.value = []
  }else {
    proxy?.$modal.msgError("上传失败："+response.msg);
  }
}
/** 导入按钮操作 */
const handleImport = (row: ShopCashierQrcodeVO | undefined) => {
  if(row) {
    uploadForm.value.id = row.id;
  }
  impDialog.visible = true;
}
/** 取消导入*/
const cancelImport = () => {
  fileList.value = [];
  impDialog.visible = false;
}
/** 打开所有*/
const handleOpenAll = async () => {
  await proxy?.$modal.confirm('确认要开启全部吗？');
  const res = await enableAll();
  if (res.code == 200) {
    proxy?.$modal.msgSuccess("全部开启成功");
    await getList();
  } else {
    proxy?.$modal.msgSuccess("全部开启成功");
  }
}
/** 关闭所有*/
const handleCloseAll = async () => {
  await proxy?.$modal.confirm('确认要关闭全部吗？');
  const res = await disableAll();
  if(res.code==200) {
    proxy?.$modal.msgSuccess("全部关闭成功");
    await getList();
  }else {
    proxy?.$modal.msgSuccess("全部关闭成功");
  }
}

onMounted(() => {
  getList();
});
</script>
